﻿using org.se.fs.presenter.IView;
using org.se.fs.presenter.Library;

namespace org.se.fs.presenter.View
{
    public class DatabaseConnection
    {
        private readonly IDatabaseConnection _view;
        private readonly ITask.IDatabaseConnection _task;
        public event FormEvent.FormEventHandler OnTestConnectFinished;
        public event FormEvent.FormEventHandler OnOkFinished;

        public DatabaseConnection(IDatabaseConnection view) : this(view, new Task.DatabaseConnection()) { }

        public DatabaseConnection(IDatabaseConnection view, ITask.IDatabaseConnection task)
        {
            _view = view;
            _task = task;
            _task.OnTestConnectFinished += TaskOnTestConnectFinished;
            _task.OnOkFinished += TaskOnOkFinished;
        }

        void TaskOnOkFinished(object source, FormEvent e)
        {
            var message = e.IsSuccess ? string.Empty : "Error in creating config file.";
            OnOkFinished(this, new FormEvent(e.IsSuccess) { Value = message });
        }

        void TaskOnTestConnectFinished(object source, FormEvent e)
        {
            var message = "Test connect " + (e.IsSuccess ? "success!" : "failed!");
            OnTestConnectFinished(this, new FormEvent(e.IsSuccess) { Value = message });
        }

        public void Initialize()
        {
            _view.ServerHost = string.Empty;
            _view.Username = string.Empty;
            _view.Password = string.Empty;
        }

        public void TestConnect()
        {
            _task.TestConnect(_view.Username, _view.Password, _view.ServerHost, Config.Database);
        }

        public void Save()
        {
            _task.SaveConfiguration(_view.Username, _view.Password, _view.ServerHost, Config.Database);
        }
    }
}
